﻿using FunnyArts.JSAdapter.Attri;
using FunnyArts.JSAdapter.Inter;
using FunnyArts.JSAdapter.Server;
using FunnyArts.PrettyClient.Core.Utils;
using FunnyArts.PrettyClient.Model;
using FunnyArts.PrettyClient.Services;
using FunnyArts.PrettyClient.Services.Contracts;
using FunnyArts.PrettyClient.ViewModels;
using Microsoft.Extensions.Configuration;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Wpf.Ui.Controls;
using Wpf.Ui.Tray;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Path = System.IO.Path;

namespace FunnyArts.PrettyClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow: IWindow
    {
        
        /// <summary>
        /// 是否为全屏模式
        /// </summary>
        private bool isFullScreen = true;
        private IConfiguration configuration;
        public MainWindowVm ViewModel { get; init; }
        public event Func<Task> interfaceLoadTask;
        public Task<List<PluginJSObject>> pluginLoadTask { get; set; }

        public MainWindow(MainWindowVm viewModel, IConfiguration configuration,  INotifyIconService notifyIconService)
        {
            InitializeComponent();
            
            this.configuration = configuration;
            this.ViewModel = viewModel;
            webView.Source = new Uri(configuration.GetSection("SystemSetting")["LoginUrl"]);
            webView.NavigationStarting += WebView2_NavigationStarting;
            //初始化系统配置
            InitSystemConfig();
            this.DataContext = this;
            notifyIconService.SetParentWindow(this);
            notifyIconService.Icon=this.Icon;
            notifyIconService.Register();
            
        }
        private async void WebView2_NavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs args)
        {
            List<IJavaScriptObject> apiBases = new List<IJavaScriptObject>();
            Task<List<PluginJSObject>> pluginLoadTask = this.pluginLoadTask;
            if (pluginLoadTask!=null&& !pluginLoadTask.IsCompleted)
            {
                pluginLoadTask.Wait();
            }
            List <PluginJSObject>  pluginJSObjects=pluginLoadTask.Result;
            foreach (var item in pluginJSObjects)
            {
                webView.CoreWebView2.AddHostObjectToScript(item.HostObjectName, item.JavaScriptObject);
                apiBases.Add(item.JavaScriptObject);
            }
            string tsClassCode2 = await apiBases.CreateAndReadJSFile();
            await webView.CoreWebView2.ExecuteScriptAsync(tsClassCode2);
            if(LoginInfo.loginUser==null)
            {
                webView.CoreWebView2.SourceChanged += WebView2_SourceChanged;
            }
        }

        private async void WebView2_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs args)
        {
            if (LoginInfo.loginUser != null)
            {
                webView.CoreWebView2.SourceChanged -= WebView2_SourceChanged;
                await interfaceLoadTask.Invoke();
                return;
            }
            string currentUrl = webView.CoreWebView2.Source;
            if (!currentUrl.Contains("login"))
            {
                // 执行 JavaScript 代码获取 Session Storage 数据
                string script = @"sessionStorage.getItem('HIS_UUHEADER');";
                string sessionStorageJson = await webView.CoreWebView2.ExecuteScriptAsync(script);
                var uuheaderStr=sessionStorageJson?.Trim('\"');
                if (!string.IsNullOrWhiteSpace(uuheaderStr))
                {
                    uuheaderStr=Regex.Unescape(uuheaderStr);
                    if (!string.IsNullOrWhiteSpace(uuheaderStr))
                    {
                        LoginInfo.loginUser = JsonConvert.DeserializeObject<User>(uuheaderStr);
                    }
                }
            }
        }

        private void InitSystemConfig()
        {
            #region 设置窗体标题
            this.ViewModel._mainFormTitle = configuration.GetSection("SystemSetting")["MainFormTitle"];
            //this.TitleBar.Title = this.ViewModel._mainFormTitle;
            #endregion

            #region 设置窗体图标
            string? titleImg = configuration.GetSection("SystemSetting")["MainFormIcon"];
            if (!string.IsNullOrWhiteSpace(titleImg))
            {
                try
                {
                    ImageSource imageSource = ConvertBase64ToImageSource(titleImg);
                    this.ViewModel._mainFormIcon = imageSource;
                    //this.TitleIcon.Source = this.ViewModel._mainFormIcon;
                }
                catch (Exception)
                {
                }
            }
            #endregion

            #region 设置窗体初始化大小
            string loadingWindowStyle = configuration.GetSection("SystemSetting")["LoadingWindowStyle"];
            if (string.IsNullOrWhiteSpace(loadingWindowStyle)) loadingWindowStyle = "Normal";
            if (loadingWindowStyle.ToUpper().Trim() == "MAX")
            {
                this.ResizeMode = ResizeMode.NoResize;
                WindowState = WindowState.Maximized;
                this.TitleBar.Visibility= Visibility.Collapsed;
                isFullScreen = true;
            }
            else if (loadingWindowStyle.ToUpper().Trim() == "MIN")
            {
                this.ResizeMode = ResizeMode.CanResize;
                WindowState = WindowState.Normal;
                this.TitleBar.Visibility = Visibility.Visible;
                isFullScreen = false;
            }else if(loadingWindowStyle.ToUpper().Trim() == "NORMAL")
            {
                this.ResizeMode =  ResizeMode.CanResize;
                WindowState = WindowState.Maximized;
                this.TitleBar.Visibility = Visibility.Visible;
                isFullScreen = false;
            }
            #endregion
        }

        private ImageSource ConvertBase64ToImageSource(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(imageBytes);
            bitmapImage.EndInit();
            return bitmapImage;
        }
        /// <summary>
        /// 主窗体案件监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.F11)
            {
                ToggleFullScreen();
            }
        }
        /// <summary>
        /// 切换全屏
        /// </summary>
        private void ToggleFullScreen()
        {
            if (isFullScreen)
            {
                this.ResizeMode = ResizeMode.CanResize;
                WindowStyle = WindowStyle.None;
                WindowStyle = WindowStyle.SingleBorderWindow;
                WindowState = WindowState.Normal;
                WindowState = WindowState.Maximized;
                this.TitleBar.Visibility = Visibility.Visible;
                isFullScreen = false;
            }
            else
            {
                this.ResizeMode = ResizeMode.NoResize;
                WindowStyle = WindowStyle.SingleBorderWindow;
                WindowStyle = WindowStyle.None;
                WindowState = WindowState.Normal;
                WindowState = WindowState.Maximized;
                this.TitleBar.Visibility = Visibility.Collapsed;
                isFullScreen = true;
            }
        }

        private void FluentWindow_Loaded(object sender, RoutedEventArgs e)
        {
            
        }
        

        private void MenuItemSetting_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.OnSystemSetting();
        }

        private void MenuItemClose_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.OnClose();
        }
    }
}
